import { Common } from "UtilsCommon";
import BaseIndex from './baseIndex';

window.entityEdit = {};

export default class EntityEdit extends BaseIndex {
  constructor() {
    super();
    this.initExpand("entityEdit");
  }

  // 弹出选择视图选择数据列表，单选，弹出层之前对DataGridView进行验证是否选择行。
  // 行为参数，DataGridView，弹出层视图 dialogView
  selectRowUpdate(props, action) {
    if (!action.parameters) this.initSelectRowUpdateAction(props, action);
    const { pageAxis } = props;

    const { dataGridView, dialogView, alertMessage } = action.parameters;
    const { udpateEntityOkActionType } = dialogView;

    const selectDataList = dataGridView.getSelectDataList();
    if (selectDataList.length === 0) {
      this.alert("请选择记录再操作！", pageAxis.showMessage, alertMessage);
      return;
    }

    const entityData = selectDataList[0];

    this.setPropertiesValue(dialogView.properties, entityData);

    if (dialogView.expandDataLoad) pageAxis.getFunction(dialogView.expandDataLoad)({ entityData, props, action });

    // 设置接收数据行数返回数据
    pageAxis.receives[udpateEntityOkActionType] = (d) => this.receiveDialogOkActionType(d, props, action);

    const onOk = (e, p) => this.setSelectRowUpdate(e, p, props, action, entityData);
    this.showdialog(action, pageAxis, dialogView, onOk);
  }

  // 弹出层确定事件行为
  setSelectRowUpdate(e, p, props, action, selectData) {
    const { dialogView } = action.parameters;
    const { pageAxis } = props;

    action.okProperty = p;

    const editProperties = dialogView.properties.filter(f => f.isEdit);

    let entityData = this.getPropertyValues(editProperties, pageAxis);
    if (dialogView.expandSetEntityData) entityData = dialogView.expandSetEntityData(entityData);

    if (entityData === false) return;

    // 获取编辑值
    const data = { oldEntityData: selectData, entityData };

    // 禁用确定按钮
    p.setDisabled(true);

    // 数据行为跟页面调用数据行为走
    pageAxis.invokeDataAction(dialogView.udpateEntityOkActionType, data);
  }

  initSelectRowUpdateAction(props, action) {
    const { pageAxis } = props;
    const dataGridView = pageAxis.getProperty(action.dataGridView);
    const dialogView = Common.arrayFirst(pageAxis.pageConfig.dialogViews, (f) => f.name === action.dialogView);
    const alertMessage = pageAxis.getProperty(action.alertMessage);

    action.parameters = { dataGridView, dialogView, alertMessage };
  }

  // 保存实体数据，包含增加与更新
  saveEntityData(props, action) {
    if (!action.parameters) this.initSaveEntityData(props, action);

    const { editView, expandSetEntityData } = action.parameters;
    const { pageAxis, property } = props;

    if (!editView.entity && editView.entityName) editView.entity = this.initEditViewEntity(editView);

    const entityData = this.getPropertyEntityData(props, editView, expandSetEntityData, action.editNames);
    if (entityData === false) return;

    if (property.confirmTip) pageAxis.confirm(property.confirmTip, () => this.saveEditEntityData(props, action, editView, entityData));
    else this.saveEditEntityData(props, action, editView, entityData);
  }

  initEditViewEntity(editView) {
    const { entityName, entityPrimaryKey } = editView;
    return { name: entityName, primaryKey: entityPrimaryKey };
  }

  saveEditEntityData(props, action, editView, entityData) {
    const { pageAxis, property, editData } = props;

    // 设置传入的编辑数据
    if (editData) for (const key in editData) entityData[key] = editData[key];

    editView.editData = entityData;

    const dataAction = action.dataAction || editView.dataAction;

    const actionType = property.saveEntityDataActionType || editView.saveEntityDataActionType || this.getDataActionType(pageAxis, dataAction, !!editView.entityData);

    if (dataAction.defaultValues) {
      dataAction.defaultValues.forEach(d => {
        if (d.Value === '$currentUserId' && pageAxis.visitUser.UserId) d.Value = pageAxis.visitUser.UserId;
      });
    }

    // 设置接收数据行数返回数据
    pageAxis.receives[actionType] = (d) => this.receiveSaveEntityDataActionType(d, props, action);

    const entityForm = action.entityForm || editView.entityForm;

    // 获取编辑值
    const data = { oldEntityData: editView.entityData, dataAction, entityForm, entity: editView.entity, entityData, pageData: pageAxis.pageData };

    // 禁用确定按钮
    property.setLoading && property.setLoading(true);

    // 数据行为跟页面调用数据行为走
    pageAxis.invokeDataAction(actionType, data);
  }

  saveEntityDataViews(props, action) {
    if (!action.parameters) this.initSaveEntityDataViews(props, action);

    const { editPropertiyViewList, expandSetEntityData } = action.parameters;
    const { pageAxis, property } = props;

    let entityData = {}; let viewEntityData = null;

    for (let i = 0; i < editPropertiyViewList.length; i++) {
      viewEntityData = this.getPropertyEntityData(props, editPropertiyViewList[i], expandSetEntityData, action.editNames);
      if (viewEntityData === false) { entityData = false; break; }
      else for (const key in viewEntityData) entityData[key] = viewEntityData[key];
    }

    if (entityData === false) return;

    const editView = editPropertiyViewList[0];

    if (property.confirmTip) pageAxis.confirm(property.confirmTip, () => this.saveEditEntityData(props, action, editView, entityData));
    else this.saveEditEntityData(props, action, editView, entityData);
  }

  getPropertyEntityData(props, view, expandSetEntityData, editNames) {
    const { pageAxis } = props;
    const { defaultEditData } = view;

    let entityData = this.getPropertyPropertiesValue(view.properties, pageAxis, editNames);

    if (view.expandSetEntityData) entityData = view.expandSetEntityData(entityData);

    if (entityData === false) return false;

    if (expandSetEntityData) entityData = expandSetEntityData({ entityData, props, view });

    if (entityData === false) return false;

    // 设置默认编辑数据
    if (defaultEditData) for (const key in defaultEditData) entityData[key] = defaultEditData[key];

    return entityData;
  }

  receiveSaveEntityDataActionType(data, props, action) {
    const { editPropertiyViewList, setDisabledViewList, successCallback } = action.parameters;
    let { editView } = action.parameters;
    if (editPropertiyViewList) editView = editPropertiyViewList[0];

    const { pageAxis, property } = props;
    if (property.isComplexEntity) setTimeout(() => property.setLoading && property.setLoading(false), 200);
    else property.setLoading && property.setLoading(false);
    if (this.isSuccessNextsProps(data, pageAxis.alert, null)) {
      if (editView.entityData) {
        editView.entityData = { ...editView.entityData, ...editView.editData }; //更新
        if (data.RowVersion) editView.entityData.RowVersion = data.RowVersion;
      }
      else if (editPropertiyViewList) {
        // 新增，清空属性值
        editPropertiyViewList.forEach(v => {
          if (v.isClear) this.setViewPropertiesValue(v.properties, null);
        });
      }
      else if (editView.isClear) this.setViewPropertiesValue(editView.properties, null); // 新增，清空属性值

      // 保存之后禁用控件
      if (setDisabledViewList) {
        // 新增，清空属性值
        setDisabledViewList.forEach(v => {
          this.setViewPropertiesDisabled(v.properties);
        });
      }

      const onOk = () => {
        if (action.toPageUrl) pageAxis.toPage(action.toPageUrl);
        else if (action.successCallback) action.successCallback({ data, props, action });
      };

      const successTip = editView.successTip || action.successTip;
      if (successCallback) successCallback({ data, props, action });
      else pageAxis.alertSuccess(successTip || "保存成功", onOk);

      if (property.setTextType && property.text2) property.setTextType(property.text2, "default");

      if (action.isRefreshList || !action.successCallback) window._DataGridView && window._DataGridView.refresh && window._DataGridView.refresh();
      if (editView.entity) window.entityEdit[editView.entity.name] = true;
    }

    return false;
  }

  initSaveEntityData(props, action) {
    const { pageAxis, property } = props;
    const editView = pageAxis.getProperty(action.editView) || property;
    const successCallback = pageAxis.getFunction(action.successCallback);
    const expandSetEntityData = pageAxis.getFunction(action.expandSetEntityData);

    let editPropertiyViewList = null;
    if (action.editPropertiyViewList) {
      editPropertiyViewList = action.editPropertiyViewList.map(m => pageAxis.getProperty(m));
    }

    let setDisabledViewList = null;
    if (action.setDisabledViewList) setDisabledViewList = action.setDisabledViewList.map(m => pageAxis.getProperty(m));

    action.parameters = { editView, editPropertiyViewList, setDisabledViewList, successCallback, expandSetEntityData };
  }

  initSaveEntityDataViews(props, action) {
    const { pageAxis } = props;
    const successCallback = pageAxis.getFunction(action.successCallback);

    const editPropertiyViewList = action.editPropertiyViewList.map(m => pageAxis.getProperty(m));

    let setDisabledViewList = null;
    if (action.setDisabledViewList) setDisabledViewList = action.setDisabledViewList.map(m => pageAxis.getProperty(m));

    action.parameters = { editPropertiyViewList, setDisabledViewList, successCallback };
  }

  getEntityData(props, action) {
    if (!action.parameters) this.initGetEntityData(props, action);

    const { editView, setRequestEntityData } = action.parameters;
    const { pageAxis } = props;

    let entityData = {};

    if (!editView.entity && action.dataAction) {
      const { entityName, primaryKey } = action.dataAction;
      editView.entity = { name: entityName, primaryKey };
    }

    if (editView.entityForm) {
      if (pageAxis.pageData.DataId) entityData.DataId = pageAxis.pageData.DataId;
    }
    else if (editView.entity && !editView.entity.isGet) {
      const { primaryKey } = editView.entity;

      let id = pageAxis.pageData[primaryKey];
      if (editView.primaryKeyValue) id = editView.primaryKeyValue;
      if (!id) return;

      entityData[primaryKey] = id;
    }

    if (editView.expandgetEntityDataParameter) entityData = editView.expandgetEntityDataParameter(entityData);

    // 设置请求实体数据
    if (setRequestEntityData) entityData = setRequestEntityData({ entityData, props, action });

    const actionType = editView.getEntityDataActionType || this.getDataActionType(pageAxis, action.dataAction);

    // 设置接收数据行为返回数据
    pageAxis.receives[actionType] = (d) => this.receivegetEntityDataActionType(d, props, action);

    const entityForm = action.entityForm || editView.entityForm;

    // 获取编辑值
    const data = { entityData, dataAction: action.dataAction, entity: editView.entity, entityForm, pageData: pageAxis.pageData };

    if (action.asyncRequest) data.asyncRequest = action.asyncRequest;

    // 数据行为跟页面调用数据行为走
    pageAxis.invokeDataAction(actionType, data);
  }

  receivegetEntityDataActionType(data, props, action) {
    const { editView, editPropertiyViewList, setGetEntityDataLoad } = action.parameters;

    const { pageAxis } = props;
    if (this.isSuccessNextsProps(data, pageAxis.alert, null)) {
      if (editView.entity && data[editView.entity.name] !== undefined) {
        data = data[editView.entity.name];
      }
      editView.entityData = data || {};
      //多个编辑视图
      if (editPropertiyViewList) {
        editPropertiyViewList.forEach(v => {
          if (!v) return;
          const name = v.propertyName || v.name;
          v.entityData = data[name] || data;
          this.setViewPropertiesValue(v.properties, v.entityData, true);

          // 扩展实体数据加载
          v.expandEntityDataLoad && v.expandEntityDataLoad();
        });
      }
      else this.setViewPropertiesValue(editView.properties, data, true);

      // 扩展实体数据加载
      editView.expandEntityDataLoad && editView.expandEntityDataLoad();

      if (setGetEntityDataLoad) setGetEntityDataLoad({ data, props, action });
    }

    return false;
  }

  initGetEntityData(props, action) {
    const { pageAxis, property } = props;
    const editView = pageAxis.getProperty(action.editView) || property;
    const setGetEntityDataLoad = pageAxis.getFunction(action.setGetEntityDataLoad);
    const setRequestEntityData = pageAxis.getFunction(action.setRequestEntityData);

    let editPropertiyViewList = null;
    if (action.editPropertiyViewList) {
      editPropertiyViewList = action.editPropertiyViewList.map(m => pageAxis.getProperty(m));
    }

    action.parameters = { editView, editPropertiyViewList, setRequestEntityData, setGetEntityDataLoad };
  }

  clearPropertyValue(props, action) {
    if (!action.parameters) this.initClearPropertyValue(props, action);

    const { pageAxis, property } = props;
    const { editView } = action.parameters;

    const properties = editView.properties.filter(f => f.isClear);

    if (property.confirmTip) pageAxis.confirm(property.confirmTip, () => this.setPropertiesValue(properties));
    else this.setPropertiesValue(properties);
  }

  initClearPropertyValue(props, action) {
    const { pageAxis } = props;
    const editView = pageAxis.getProperty(action.editView);

    action.parameters = { editView };
  }

  deleteEntityData(props, action) {
    if (!action.parameters) this.initDeleteEntityData(props, action);

    const { pageAxis, property } = props;
    const { editView } = action.parameters;

    const actionType = editView.deleteEntityDataActionType || this.getDataActionType(pageAxis, action.dataAction);

    const entityData = editView.entityData || property.entityData;
    if (!entityData) return;

    // 设置接收数据行数返回数据
    pageAxis.receives[actionType] = (d) => this.receiveDeleteEntityData(d, props, action);

    const onOk = () => {
      property.setDisabled && property.setDisabled(true);

      pageAxis.invokeDataAction(actionType, { entity: editView.entity, entityData, dataAction: action.dataAction });
    };

    const confirmTip = property.confirmTip || action.confirmTip;

    if (confirmTip) pageAxis.confirm(confirmTip, onOk);
    else onOk();
  }

  receiveDeleteEntityData(data, props, action) {
    const { pageAxis, property } = props;
    property.setDisabled && property.setDisabled(false);

    const { editView } = action.parameters;

    const successTip = property.successTip || action.successTip;

    if (this.isSuccessNextsProps(data, pageAxis.alert)) {
      if (action.successCallback) {
        pageAxis.getFunction(action.successCallback)({ data, property, action });
      }
      else {
        window._DataGridView && window._DataGridView.refresh && window._DataGridView.refresh();
        pageAxis.alertSuccess(successTip, () => pageAxis.toBack());
        if (editView.entity) window.entityEdit[editView.entity.name] = true;
      }
    }
    return false;
  }

  initDeleteEntityData(props, action) {
    const { pageAxis } = props;
    const editView = pageAxis.getProperty(action.editView) || {};

    action.parameters = { editView };
  }
}
